import {validatenull} from "/src/utils/validate.js";
import {getStore} from "/src/utils/store.js";
import {useUserStore} from "../store/modules/user.js";
import {reactive, ref, getCurrentInstance} from "vue"
import website from "@/config/website.js";

export function useIndexHook() {
    const cxt = getCurrentInstance()

    //刷新token锁
    const refreshLock = ref(false)
    //刷新token的时间
    const refreshTime = ref("")

    const optionData = reactive({
        refreshLock, refreshTime
    })

    function created() {
        //实时检测刷新token
        refreshToken();
    }

    created()

    // 10分钟检测一次token
    function refreshToken() {
        const dayjs = cxt.appContext.config.globalProperties.$dayjs
        const website = cxt.appContext.config.globalProperties.website

        optionData.refreshTime = setInterval(() => {
            const token = getStore({
                name: "token", debug: true
            }) || {};
            let date1 = dayjs(token.datetime);
            let date2 = dayjs()
            const date = date2.diff(date1, 'seconds')
            if (validatenull(date)) return;
            if (date >= website.tokenTime && !optionData.refreshLock) {
                optionData.refreshLock = true;
                const userStore = useUserStore()
                userStore.RefreshToken().then(() => {
                    optionData.refreshLock = false;
                }).catch(() => {
                    optionData.refreshLock = false;
                });
            }
        }, 1000);
    }

}